package com.eii.system.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.eii.common.constant.BusinessTypeConstants;
import com.eii.common.model.auth.LoginAppUser;
import com.eii.common.utils.StringUtils;
import com.eii.common.web.controller.BaseController;
import com.eii.common.web.domain.Result;
import com.eii.log.annotation.AuditLog;
import com.eii.oauth2.common.util.SecurityUtils;
import com.eii.system.api.client.feign.RemoteFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.eii.system.api.domain.SysFile;
import com.eii.system.api.domain.SysUser;
import com.eii.system.api.model.LoginUser;
import com.eii.system.service.ISysUserService;

/**
 * 个人信息 业务处理
 */
@RestController
@RequestMapping("/user/profile")
public class SysProfileController extends BaseController {

    private final static String CONTROLLER_TITLE = "个人信息";

    @Autowired
    private ISysUserService userService;

//    @Autowired
//    private TokenService tokenService;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 个人信息
     */
    @GetMapping
    public Result profile() {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", user);
        resultMap.put("roleGroup", userService.selectUserRoleGroup(username));
        resultMap.put("postGroup", userService.selectUserPostGroup(username));
        return Result.success(resultMap);
    }

    /**
     * 修改用户
     */
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.UPDATE)
    @PutMapping
    public Result updateProfile(@RequestBody SysUser user) {
        LoginAppUser loginAppUser = SecurityUtils.getLoginAppUser();
        //TODO：调整用户获取
//        SysUser sysUser = loginAppUser;
        /*user.setUserName(sysUser.getUserName());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return Result.fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return Result.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserId(sysUser.getUserId());
        user.setPassword(null);
        if (userService.updateUserProfile(user) > 0) {
            // 更新缓存用户信息
            loginUser.getSysUser().setNickName(user.getNickName());
            loginUser.getSysUser().setPhonenumber(user.getPhonenumber());
            loginUser.getSysUser().setEmail(user.getEmail());
            loginUser.getSysUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return Result.success();
        }*/
        return Result.fail("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.UPDATE)
    @PutMapping("/updatePwd")
    public Result updatePwd(String oldPassword, String newPassword) {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return Result.fail("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return Result.fail("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(username, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            LoginAppUser loginAppUser = SecurityUtils.getLoginAppUser();
            //TODO：更新缓存用户密码
//            loginUser.getSysUser().setPassword(SecurityUtils.encryptPassword(newPassword));
//            tokenService.setLoginUser(loginUser);
            return Result.success();
        }
        return Result.fail("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.UPDATE)
    @PostMapping("/avatar")
    public Result avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            // 更新缓存用户密码
            LoginAppUser loginAppUser = SecurityUtils.getLoginAppUser();
            Result<SysFile> fileResult = remoteFileService.upload(file);
            if (fileResult == null || fileResult.getData() == null) {
                return Result.fail("文件服务异常，请联系管理员");
            }
            //TODO：更新缓存用户密码
//            String url = fileResult.getData().getUrl();
//            if (userService.updateUserAvatar(loginUser.getUsername(), url)) {
//                Result ajax = Result.success();
//                ajax.put("imgUrl", url);
//                // 更新缓存用户头像
//                loginUser.getSysUser().setAvatar(url);
//                tokenService.setLoginUser(loginUser);
//                return ajax;
//            }
        }
        return Result.fail("上传图片异常，请联系管理员");
    }
}
